package Thread;

import java.util.concurrent.*;

public class Demo34 {
    public static void main(String[] args) {
        //1,配置线程池参数
        int corePoolSize = 5; //核心线程数
        int maximumPoolSize = 10; //最大线程数：核心+临时
        long keepAliveTime = 30; //临时线程空闲存活时间/s
        TimeUnit unit = TimeUnit.SECONDS; //存活时间单位：s
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(3);  //任务队列：阻塞队列
        //线程工厂：创建线程
        ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r);
            }
        };
        //拒绝策略：队列满+线程满时，抛出异常
        RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
        //2，创建线程池
        ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                rejectedExecutionHandler
        );
        //3,提交任务
        for (int i = 0; i < 10; i++) {
            int id=i;
            threadPoolExecutor.submit(()->{
                System.out.println(Thread.currentThread().getName()+" "+id);
            });
        }
        threadPoolExecutor.shutdown();
    }





    public static void main1(String[] args) throws InterruptedException {
        ExecutorService threadPool1 = Executors.newCachedThreadPool(); //数量大
        ExecutorService threadPool2 = Executors.newFixedThreadPool(10); //固定线程数量
        for (int i = 0; i < 100; i++) {
            int idx = i;
            threadPool2.submit(() -> {
                System.out.println(Thread.currentThread().getName() + ":" + idx);
            });
        }
        threadPool2.awaitTermination(1000, TimeUnit.SECONDS); //等待线程中的线程全部执行完毕
        threadPool2.shutdown(); //把线程池里的线程全部关闭，不能保证任务全部完成
    }
}
